<template>
  <div class="form-container">
    <div class="form-contain">
      <div class="form-title">发布帖子</div>
      <a-form
          id="form"
          :form="form"
          v-bind="formItemLayout"
          @submit="addPostSubmit"
      >
        <a-form-item label="标题">
          <a-input
              placeholder="请输入帖子标题，能吸引更多的人看哦"
              v-decorator="['postTitle', { rules: [{ required: true, message: '请输入帖子标题!' }] }]"
          />
        </a-form-item>

        <a-form-item label="内容描述">
          <a-textarea
              v-decorator="['postText', { rules: [{ required: true, message: '请输入帖子内容!' }]}]"
              placeholder="说点好玩的"
              :auto-size="{ minRows: 4, maxRows: 7 }"
          />
        </a-form-item>

        <a-form-item label="是否匿名">
          <a-switch
            checked-children="是"
            un-checked-children="否"
            v-decorator="['isAnonymous', { valuePropName: 'checked' }]"
          />
        </a-form-item>

        <a-form-item label="图片" extra="最多可上传8张">
          <a-upload
            :multiple="true"
            list-type="picture-card"
            @preview="handlePreview"
            @customRequest="picRequest"
            @change="handleChange"
            :file-list="fileList"
            :beforeUpload="beforeUpload"
          >
            <div v-if="fileList.length < 9">
              <a-icon type="plus" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-form-item>

        <a-form-item :wrapper-col="{ span: 12, offset: 10 }">
          <a-button type="primary" html-type="submit">
            发布
          </a-button>
          <a-button :style="{ marginLeft: '60px' }" @click="handleReset">
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </div>

  </div>
</template>

<script>
import {addPost} from "@/api";

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
export default {
  name: "Post",
  data:() => ({
    // form: this.$form.createForm(this, { name: 'upload-form' }),
    formItemLayout: {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 }
    },
    previewVisible: false,
    previewImage: '',
    fileList: [
      // {
      //   uid: '-1',
      //   name: 'image.png',
      //   status: 'done',
      //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
      // },
    ],
  }),
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'validate_other' });
  },
  methods: {
    //图片上传
    picRequest(){
      console.log("我是图片上传",this.fileList)
    },
    //图片上传之前事件
    beforeUpload(file, fileList){
      this.fileList = [...this.fileList, file];
      console.log('fileList', file,fileList)
      return false
    },
    //新增帖子
    addPostSubmit(e) {
      let data;
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          const { fileList } = this;
          data = this.form.getFieldsValue()
          data.userName = window.localStorage.getItem('userName')
          if (data.isAnonymous === '否') {
            data.isAnonymous = 0
          }else {
            data.isAnonymous = 1
          }
          if(data) {
            let formData = new FormData();
            formData.append("postTitle", data.postTitle);
            formData.append("postText", data.postText);
            formData.append("userName", data.userName)
            formData.append("isAnonymous", data.isAnonymous)
            fileList.forEach(file => {
              console.log('文件',file)
              formData.append('images', file);
            });
            addPost(formData)
              .then((res) => {
                if (res.status == 200){
                  this.$message.success('发帖成功！');
                  this.fileList = []
                  this.handleReset()
                }else{
                  this.$message.info(res.msg);
                }
              })
              .catch((err) => {
                this.$message.error(err);
              })
          }
        }
      });
    },
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange(info) {
      if (info.file.status === 'done') {
        this.fileList = info.file.originFileObj
      }
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values);
        }
      });
    },
    normFile(e) {
      console.log('Upload event:', e);
      if (Array.isArray(e)) {
        return e;
      }
      return e && e.fileList;
    },
    handleReset() {
      this.form.resetFields();
    },
  },
}
</script>

<style scoped>
  .form-container {
    display: flex;
    justify-content: center;
  }
  .form-contain {
    width: 1000px;
    padding: 0px 30px 30px 30px;
    border-radius: 10px;
    border: 1px solid #5DD5C8;
    margin: 50px 0px;
  }
  .form-title {
    font-size: 20px;
    font-weight: bold;
    text-align: center;
    padding: 20px;
    border-bottom: 1px solid #97f3e9;
  }
  #form {
    margin-top: 30px;
  }
</style>